/**
 * @Author: lena
 * @Description:实现copy文件到另一文件的方法
 * @Version: 1.0.0
 * @Date: 2021/9/6 11:52
 */

package filex

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// Copy1 使用bufio：将read.go的内容拷贝到test.txt中
func Copy1() {
	// 先读取文件内容:bufio.NewReader
	file, err := os.Open("./exercise/file/read.go") // (*File, error)
	if err != nil {                                 // 如果没有报错,则err为<nil>
		fmt.Println("read err :", err)
		return
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	// 写入的文件:bufio.NewWriter
	file1, err := os.OpenFile("./exercise/file/test.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Println("write err :", err)
		return
	}
	defer file1.Close()
	writer := bufio.NewWriter(file1)
	for {
		// reader读取到delim停止 func (b *Reader) ReadString(delim byte) (string, error)
		readString, err := reader.ReadString('\n')
		if err == io.EOF {
			// 文件读完了但是还有数据没有输出
			if len(readString) != 0 {
				writer.WriteString(readString)
				writer.Flush()
			}
			return
		}
		if err != nil {
			fmt.Println("read err :", err)
			return
		}
		writer.WriteString(readString)
		writer.Flush()
	}
}

// Copy2 使用io.copy实现
func Copy2(fromSrc, toSrc string) (written int64, err error) {
	// 读取
	read, err := os.Open(fromSrc) // (*File, error)
	if err != nil {               // 如果没有报错,则err为<nil>
		fmt.Println("read err :", err)
		return
	}
	defer read.Close()
	reader := bufio.NewReader(read)
	// 写入
	write, err := os.OpenFile(toSrc, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Println("write err :", err)
		return
	}
	defer write.Close()
	writer := bufio.NewWriter(write)
	// 拷贝
	return io.Copy(writer, reader)
}

/*func main() {
	_, err := file.Copy2("./exercise/file/read.go", "./exercise/file/test.txt")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("ok")
}*/
